/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import StandardTable from "@/components/StandardTable";
import { debounce, isEmpty } from "lodash";
import { Row, Col, Button } from "antd";
import Modal from "./modal";
import SearchBar from "./search";
import pageConfig from "./config";

@connect(({ loading, setter, source }) => {
  return {
    setter,
    source,
    loadingEffects: loading.effects,
  };
})
export default class OperatorSetting extends Component {
  handleTableChange = debounce(
    pagination => {
      const { dispatch } = this.props;
      const { formValues } = this.state;
      const { actionTypes } = this.pageConfig;
      const page = pagination.current;
      this.setState({ page });
      dispatch({
        type: actionTypes.getSetterList,
        payload: {
          ...formValues,
          page,
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  constructor(props) {
    super(props);
    const { sourceType } = props;
    this.pageConfig = pageConfig.call(this, sourceType);
    const { columns, getSetterList } = this.pageConfig;
    this.searchFormRef = React.createRef();
    this.state = {
      visible: false,
      hasOrderSource: 0, // 是否有单号源，0：没有
      selectedRows: [],
      tableData: [],
      disabled: true,
      page: 1,
    };
    this.brand = {
      dp: "德邦",
      ems: "EMS",
      gt: "国通",
      ht: "百世",
      jt: "极兔",
      post: "邮政",
      postx: "邮政小包",
      se: "速尔",
      sf: "顺丰",
      sto: "申通",
      tt: "天天",
      yd: "韵达",
      ys: "优速",
      yt: "圆通",
      zjs: "宅急送",
      zt: "中通",
    };
    this.columns = columns;
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { page } = this.state;
    const { actionTypes } = this.pageConfig;
    dispatch({
      type: actionTypes.getSetterList,
      payload: {
        page,
        site_id: "all",
        keyword: "",
      },
    });
    // 下拉框的数据
    dispatch({
      type: "setter/getOperatorOrderSourceList",
    });
    // 判断单号源有没有
    dispatch({
      type: "source/getAllSource",
    }).then(res => {
      this.hasOrderSource(res.data);
    });
  }

  componentDidUpdate(prevProps) {
    const {
      source: { allSource },
    } = this.props;
    const old_allSource = prevProps.source.allSource;
    const oldSourceLength = this.getSourceLength(old_allSource);
    const newSourceLength = this.getSourceLength(allSource);
    if (oldSourceLength !== newSourceLength) {
      this.hasOrderSource(allSource);
    }
  }

  onTriggerModal(open, waybill_source, user_id = "") {
    const {
      setter: { selectData },
    } = this.props;
    const default_waybill_source = []; // 当单号源操作为新增关系时，设置默认的单号源设置表格数据
    let I = 0;
    for (const key in selectData) {
      if (Object.hasOwnProperty.call(selectData, key)) {
        const arr = [];
        const obj = {};
        const value = selectData[key];
        // 通过已有单号源的品牌，设置默认的单号源操作表格数据
        for (const skey in value) {
          if (Object.hasOwnProperty.call(value, skey)) {
            arr.push({ [skey]: value[skey] });
            obj.selectData = arr;
            obj.brand_type = key;
            obj.brand_name = this.brand[key];
            obj.id = I--; // 表格每行数据的唯一标识
            obj.price = 0.0;
            obj.source = {};
            obj.status = "1";
            obj.is_infinite = "1";
            obj.quantity = "-1";
          }
        }
        default_waybill_source.push(obj);
      }
    }

    // 判断状态是否是暂无，暂无则使用默认的default_waybill_source去渲染单号源设置表格
    if (waybill_source.length > 0 && waybill_source[0].id == 0) {
      this.setState({
        visible: open,
        tableData: default_waybill_source,
        user_id,
      });
    } else {
      /**
       * 当点击单号源操作时，对比从设置中带过来的waybill_source数据与默认的default_waybill_source，
       * 通过判断快递品牌，将waybill_source覆盖到default_waybill_source上，达到显示已有单号源关系的默认效果
       *  */

      for (let i = 0; i < default_waybill_source.length; i++) {
        const item = default_waybill_source[i];
        for (let j = 0; j < waybill_source.length; j++) {
          const element = waybill_source[j];
          element.is_infinite = element.waybill_quantity < 0 ? "1" : "0";
          if (item.brand_type == element.brand_type) {
            default_waybill_source.splice(i, 1, element); // 将最新的数据替换默认的数据
          }
        }
      }
      const tableData = default_waybill_source;

      this.setState({
        visible: open,
        tableData,
        user_id,
      });
    }
  }

  // 获取单号源的数量
  getSourceLength = data => {
    return Object.keys(data)
      .map(() => {
        const thirdLength = data.third
          .map(iitem => iitem.list[0].source.length)
          .reduce((prev, curn) => prev + curn, 0);
        return data.kop.length + thirdLength;
      })
      .reduce((prev, curn) => curn, 0);
  };

  hasOrderSource = data => {
    if (isEmpty(data)) {
      this.setState({ hasOrderSource: 0 });
      return;
    }
    const keyLength = Object.keys(data)
      .map(item => {
        return data[item].length;
      })
      .reduce((prev, curn) => prev + curn);

    if (keyLength > 0) {
      // 有单号源
      this.setState({
        hasOrderSource: 1,
      });
    } else {
      this.setState({ hasOrderSource: 0 });
    }
  };

  onRowSelect = selectedRows => {
    const disabled = selectedRows.length == 0;
    this.setState({
      selectedRows,
      disabled,
    });
  };

  cleanSelectRows = () => {
    this.setState({
      selectedRows: [],
      disabled: true,
    });
  };

  modalFormRef = formRef => {
    this.formRef = formRef;
  };

  getFormVlues = values => {
    this.setState({ formValues: values });
  };

  modifyBatch() {
    const { selectedRows } = this.state;
    const arr = [];
    const user_id = [];
    selectedRows.forEach(item => {
      user_id.push(item.user_id || item.cm_id);
    });
    this.onTriggerModal(true, arr, user_id.join(","));
  }

  render() {
    const {
      visible,
      hasOrderSource,
      tableData,
      selectedRows,
      user_id,
      disabled,
      page,
    } = this.state;
    const {
      stateNameConfig: { setterList },
      actionTypes: { getSetterList },
    } = this.pageConfig;
    const { setter, changeActiveKey, sourceType, loadingEffects } = this.props;
    const stateList = setter[setterList];
    const isEmptyList = !!(stateList.list == null || stateList.list.length == 0);
    return (
      <div>
        <SearchBar
          isEmptyList={isEmptyList}
          getValues={this.getFormVlues}
          sourceType={sourceType}
          changeActiveKey={changeActiveKey}
        />
        <StandardTable
          rowKey={record => record.user_id || record.cm_id}
          columns={this.columns}
          data={stateList}
          loading={loadingEffects[getSetterList]}
          selectedRows={selectedRows}
          onSelectRow={this.onRowSelect}
          onChange={this.handleTableChange}
        />
        <Row style={{ position: "absolute", bottom: "15px" }}>
          <Col>
            <Button disabled={disabled} type="primary" onClick={this.modifyBatch.bind(this)}>
              批量设置单号源
            </Button>
          </Col>
        </Row>
        <Modal
          changeActiveKey={changeActiveKey}
          wrappedComponentRef={this.modalFormRef}
          visible={visible}
          okText="保存"
          tableData={tableData}
          user_id={user_id}
          title="设置单号源给业务员使用"
          hasOrderSource={hasOrderSource}
          hideModal={() => this.onTriggerModal(false, [])}
          page={page}
          cleanSelectRows={this.cleanSelectRows}
          sourceType={sourceType}
        />
      </div>
    );
  }
}
